package proj.unions.resource;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import proj.unions.general.OnMyCallBack;
import proj.unions.general.OnMyClickedListener;
import proj.unions.general.ProperTiesCondefine;
import proj.unions.general.PropertiesData;
import proj.unions.general.SCDialog;
import proj.unions.general.SuperTools;
import proj.unions.general.Text;
import android.app.Activity;
import android.util.Xml;

public class CheckAPKVersion implements Runnable, RMConstDefine {
	
	private Activity mActivity = null;
	private OnMyCallBack mOnMyCallBack = null;
	
	public CheckAPKVersion(Activity a, OnMyCallBack l)
	{
		mActivity = a;
		mOnMyCallBack = l;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		if (mActivity == null || mOnMyCallBack == null)
		{
			mOnMyCallBack.onReceive("error", 0, null);
			return;
		}

		check();
	}

	private void check()
	{
		//旧包还在先删除
		String oldAPK = SuperTools.getInstance().getInstallAPKPath() + 
				Integer.valueOf(SuperTools.getInstance().getVersionCode()) + ".apk";
		SuperTools.getInstance().deleteFile(oldAPK);
		
		String address = PropertiesData.getInstance().getString(ProperTiesCondefine.HOST_URL);
		String versionCode = SuperTools.getInstance().getVersionCode();
		String unionId = PropertiesData.getInstance().getString(ProperTiesCondefine.UNION_ID);
		String url = PropertiesData.getInstance().getString(ProperTiesCondefine.CHECK_APK_URL, address, versionCode, unionId);
		
		int code = -1;
		try {
			HttpGet getMethod = new HttpGet(url);
			HttpClient httpClient = new DefaultHttpClient();
			HttpResponse response = httpClient.execute(getMethod);
			code = response.getStatusLine().getStatusCode();
			if (code == 200)
			{
				InputStream is = response.getEntity().getContent();
				try {
					parse(is);
					return;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SuperTools.getInstance().showErrorDialog(Text.getKey("Net")/*"网络"*/, Text.getKey("Net_CallManager_ErrorNet")/*"网络连接异常，请联系管理员*/ + " Error:" + code);
	}
	
	private void parse(InputStream is) throws Exception
	{
		byte[] buffer = new byte[1024];
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int count = 0;
		while((count=is.read(buffer)) != -1)
		{
			bos.write(buffer, 0, count);
		}
		buffer = bos.toByteArray();
		ByteArrayInputStream bis = new ByteArrayInputStream(buffer);
		
		JSONObject json = new JSONObject();
		
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(bis,"UTF-8");
		int eventType = parser.getEventType();
		while(eventType != XmlPullParser.END_DOCUMENT)
		{
			switch(eventType)
			{
			case XmlPullParser.START_DOCUMENT:
				break;
			case XmlPullParser.START_TAG:
				String startName = parser.getName();
				
				if(parser.getName().equals("update"))
				{
					int attributeCount = parser.getAttributeCount();
					for(int i = 0; i < attributeCount; ++i)
					{
						String name = parser.getAttributeName(i);
						String value = parser.getAttributeValue(i).trim();
						if(name.equals(KEY_NEWEST_VERSION))
						{
							json.put(KEY_NEWEST_VERSION, Integer.valueOf(value));
						}
						else if(name.equals(KEY_CLIENT_VERSION))
						{
							json.put(KEY_CLIENT_VERSION, Integer.valueOf(value));
						}
						else if(name.equals(KEY_IS_UPDATE))
						{
							json.put(KEY_IS_UPDATE, Boolean.valueOf(value));
						}
					}
				}
				else if(parser.getName().equals("file"))
				{
					int attributeCount = parser.getAttributeCount();
					for(int i = 0; i < attributeCount; ++i)
					{
						String name = parser.getAttributeName(i);
						String value = parser.getAttributeValue(i).trim();
						if(name.equals("type"))
						{
							if(value.equals("apk"))
							{
								
							}
							else if(value.equals("lib"))
							{
								
							}
							else if(value.equals("res"))
							{
								
							}
						}
						else if(name.equals("url"))
						{
							json.put(KEY_APK_URL, value);
						}
						else if(name.equals("dmp"))
						{
							
						}
						else if(name.equals("ver"))
						{
							
						}
					}
				}
				break;
			case XmlPullParser.END_TAG:
				String endName = parser.getName();
				
				break;
			}
			eventType = parser.next();
		}
		
//		mOnMyCallBack.onReceive("yes", 1, json);
		compare(json);
	}
	
	private void compare(final JSONObject json)
	{
		try {	
			if(json.isNull(KEY_APK_URL) || json.isNull(KEY_IS_UPDATE))
			{
				mOnMyCallBack.onReceive("yes", 0, json);
				return;
			}
			int clientVersion = Integer.valueOf(SuperTools.getInstance().getVersionCode());
			int newestVersion = json.getInt(KEY_NEWEST_VERSION);
			boolean needUpdate = json.getBoolean(KEY_IS_UPDATE);
			//对比版本
			if (clientVersion < newestVersion && needUpdate)
			{
				//提示有更新
				mActivity.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub

//						SCDialog.create(mActivity, "更新提示", "APK有新的版本!", "确定", "", new OnMyClickedListener() {
//							
//							@Override
//							public void onPositive(JSONObject data) {
//								// TODO Auto-generated method stub
//								
//							}
//							
//							@Override
//							public void onNegative(JSONObject data) {
//								// TODO Auto-generated method stub
//								mOnMyCallBack.onReceive("yes", 1, json);
//							}
//						}).show();
						mOnMyCallBack.onReceive("yes", 1, json);
					}
				});
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//新的版本号
		
	}
}
